import asyncio
import time
import json
import pymysql
import requests
from login_ls import main
import configparser
conf = configparser.ConfigParser()
conf.read('../config.ini')

conn = pymysql.connect(host=conf['MYSQL']['HOST'], port=int(conf['MYSQL']['PORT']), user=conf['MYSQL']['USER'], password=conf['MYSQL']['PASSWORD'], db='smp_data', charset='utf8',autocommit=True)
cur = conn.cursor()
def run():
    zhs = {
        "阳光雨露服务中心": ("jd_UNmmvemPIMdn", "zyq1103."),
        # '阳光多品牌': ('18101023889', 'lenovo3c@'),
    }
    STATUSLISTS = {'ZERO': '初审通过,待服务商接单', 'ONE': '已接单,待接机', 'WAIT_REPORT_INFO': '已接单,待客户填写相关信息', 'WAIT_VISIT': '已接单,待等待上门取货',
     'WAIT_ARRIVE_STORE': '已接单,待客户送货至门店', 'EXPRESS_INFO_FINISH': '信息已完善,待接机', 'TWO': '已接机,待服务商提交维修方案',
     'THREE': '提交方案待审核', 'FOUR': '审核通过,待维修', 'FIRVE': '审核不通过', 'START_MAINTAIN': '维修中', 'MAINTAIN_FINISH': '商品维修结束,待寄送',
     'MAINTAIN_FINISH_WAIT_VISIT': '商品维修结束,待上门送货', 'MAINTAIN_FINISH_WAIT_SHORE': '商品维修结束,待客户到门店取商品',
     'RETURN_GOODS': '已寄送,待确认收货', 'CUSTOMER_RECEIVE': '客服确认收货,待反馈结果', 'RETURN_MAINTAIN': '客户不满意,待客服沟通,确认是否返修',
     'SERVICE_ORDER_END': '服务单结单', 'CHANGE_SERVICE': '改派', 'RETURN': '返修,待处理', 'CANCEL': '取消履约',
     'MAINTAIN_FINISH_WAIT_PAY': '待打款', 'FINISH_PAY': '已打款', 'FAIL_PAY': '打款失败'}
    for zh in list(zhs.keys()):
        username = zhs[zh][0]
        password = zhs[zh][1]
        cookies = asyncio.get_event_loop().run_until_complete(main(zh, username, password))
        cookie = {}
        for i in cookies:
            cookie[i['name']] = i['value']
        headers = {
            'accept': 'application/json, text/plain, */*',
            'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            'appcode': 'lvshengSP',
            'Content-Type': 'application/json',
            'origin': 'https://digital-ins.jd.com',
            'priority': 'u=1, i',
            'referer': 'https://digital-ins.jd.com/',
            'sec-ch-ua': '"Chromium";v="134", "Not:A-Brand";v="24", "Microsoft Edge";v="134"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-site',
            'systype': '1',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 Edg/134.0.0.0',
            'userid': 'jd_UNmmvemPIMdn',
        }
        # smp获取需要爬取的工单
        GetLsStateUpdateList = requests.post('https://smpjoy3c.sunits.com/JdLsOrder/GetLsStateUpdateList',headers={"Token": "JDLSPASSWORDS"})
        order_info = GetLsStateUpdateList.json()['rows']
        print('一共有{}条数据'.format(len(order_info)))
        for item in order_info:
            Id = item['Id']
            performingId = item['LsCode']
            # 获取本率盛订单订单详情数据
            # 1) 获取店铺数据
            shopCode_id = requests.post('https://baozang-out.jd.com/serviceOrder/queryBindShopInfo', headers=headers,cookies=cookie)
            data_values_status = 1
            data_values = []
            for index1, shop_info in enumerate(shopCode_id.json()['values']):
                print('正在获取{}店铺下的订单'.format(shop_info['name']))
                shop_code = shop_info['code']
                data_json = {"pageIndex": 1, "pageSize": 10,
                             "query": {"serviceState": None, "shopCode": shop_code, "orderId": None,
                                       "performingId": performingId.replace(' ', ''), "serviceOrderNo": None, "phone": None,
                                       "facilitatorCode": None, "expressNo": None, "createTime": None, "endTime": None}}
                data = json.dumps(data_json)
                search_phone_res = requests.post(
                    'https://baozang-out.jd.com/serviceOrder/queryFacilitatorOrderByStateAndCode', headers=headers,
                    cookies=cookie, data=data)
                data_values = search_phone_res.json()['values']
                if data_values == []:
                    if index1 == 3:
                        data_values_status = 0
                        break
                    continue
                else:
                    break
            if data_values_status == 0:
                continue
            serviceState = data_values[0]['serviceState']
            status = STATUSLISTS[serviceState]  # 当前状态
            # 获取详情页数据
            # detail_data = {
            #     "serviceOrderNo": data_values[0]['serviceOrderNo'],
            #     "facilitatorCode": data_values[0]['facilitatorCode'],
            #     "shopCode": data_values[0]['shopCode'],
            #     "performingOrderState": data_values[0]['serviceState'],
            # }
            # detail_data = json.dumps(detail_data)
            # details_res = requests.post('https://baozang-out.jd.com/serviceOrder/serviceOrderDetail', headers=headers,cookies=cookie, data=detail_data)
            # details_val = details_res.json()['value']
            # newMachinePrice = details_val['planCommitInfoDto']['maintainOrderCommitFeeDetailDto']['newMachinePrice'] # 新机费
            # userPayAmount = details_val['planCommitInfoDto']['maintainOrderCommitFeeDetailDto']['userPayAmount']  # 用户支付金额
            # subsidyFee = details_val['planCommitInfoDto']['maintainOrderCommitFeeDetailDto']['subsidyFee']  # 用户免补金额
            UpdateLsStateData = {"Id":Id,"State":status}
            UpdateLsStateRes = requests.post('https://smpjoy3c.sunits.com/jdlsorder/UpdateLsState',data=json.dumps(UpdateLsStateData),headers={"Token": "JDLSPASSWORDS"})
            if UpdateLsStateRes.json()['success']:
                print('状态上传成功')
            else:
                print('状态上传失败')
            # UpdateLsFeeInfoData = {"Id":Id,"CustomerPay":userPayAmount,"CustomerExemptPay":subsidyFee,"NewMachineFee":newMachinePrice}
            # UpdateLsFeeInfoRes = requests.get('https://smpjoy3c.sunits.com//jdlsorder/UpdateLsFeeInfo',data=json.dumps(UpdateLsFeeInfoData), headers={"Token": "JDLSPASSWORDS"})
            # if UpdateLsFeeInfoRes.json()['success']:
            #     print('支付数据上传成功')
            # else:
            #     print('支付数据上传失败')



if __name__ == '__main__':
    run()